const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: ''
    },
    hasUserInfo: false
  },

  onLoad() {
    // 检查是否已经授权
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userInfo']) {
          // 已授权，直接获取用户信息
          wx.getUserInfo({
            success: (res) => {
              this.setData({
                userInfo: res.userInfo,
                hasUserInfo: true
              });
            }
          });
        }
      }
    });
  },

  getUserProfile() {
    // 使用 wx.getUserProfile 获取用户信息
    wx.getUserProfile({
      desc: '展示用户信息',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
      },
      fail: (err) => {
        console.log('用户拒绝授权', err);
      }
    });
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.updateUserInfo({ avatarUrl });
  },

  onInputChange(e) {
    const nickName = e.detail.value;
    this.updateUserInfo({ nickName });
  },

  updateUserInfo(newInfo) {
    const updatedUserInfo = { ...this.data.userInfo, ...newInfo };
    const hasUserInfo = updatedUserInfo.nickName && updatedUserInfo.avatarUrl && updatedUserInfo.avatarUrl !== defaultAvatarUrl;
    this.setData({
      userInfo: updatedUserInfo,
      hasUserInfo: hasUserInfo
    });
  },
  getuserinfo() {
    // wx登录
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          const code = res.code;
          // 获取微信用户信息
          wx.getUserInfo({
            success: function(res) {
              //用户信息
              const userInfo = res.userInfo;
              //性别 0：未知、1：男、2：女
              const { nickName, avatarUrl, gender, province, city, country } = userInfo;

              uni.setStorageSync('userInfo', userInfo);
              uni.navigateTo({
                url: './wxinfo/wxinfo'
              });
            },
            fail: res => {
              // 获取失败的去引导用户授权
              uni.showToast({
                title: '您需要授权，才能获取您的信息！'
              });
            }
          });
        } else {
          //
        }
      }
    });
  }
});
